from sqlalchemy import or_
from app import db
from app.models.role import Role, RoleMenu
from app.models.menu import Menu


class RoleService:
    """角色服务层"""
    
    @staticmethod
    def get_list(page=1, per_page=10, keyword=None, status=None):
        """获取角色列表"""
        query = Role.query
        
        # 关键词搜索
        if keyword:
            query = query.filter(Role.name.like(f'%{keyword}%'))
        
        # 状态筛选
        if status is not None:
            query = query.filter(Role.status == status)
        
        # 按创建时间降序排列
        query = query.order_by(Role.create_time.desc())
        
        return query, page, per_page
    
    @staticmethod
    def get_by_id(role_id):
        """根据ID获取角色"""
        return Role.query.get(role_id)
    
    @staticmethod
    def create(data):
        """创建角色"""
        role = Role()
        role.name = data.get('name')
        role.key = data.get('key')
        role.description = data.get('description')
        role.data_scope = data.get('data_scope', 'dept')  # 默认部门权限，更安全
        role.status = data.get('status', True)
        role.sort = data.get('sort', 0)
        
        db.session.add(role)
        db.session.commit()
        return role
    
    @staticmethod
    def update(role_id, data):
        """更新角色"""
        role = Role.query.get(role_id)
        if not role:
            return None
        
        role.name = data.get('name', role.name)
        role.key = data.get('key', role.key)
        role.description = data.get('description', role.description)
        role.data_scope = data.get('data_scope', role.data_scope)
        role.status = data.get('status', role.status)
        role.sort = data.get('sort', role.sort)
        
        db.session.commit()
        return role
    
    @staticmethod
    def delete(role_id):
        """删除角色"""
        role = Role.query.get(role_id)
        if not role:
            return False
        
        # 检查是否有关联的管理员
        if role.admins:
            return False, "该角色下存在管理员，无法删除"
        
        db.session.delete(role)
        db.session.commit()
        return True, "删除成功"
    
    @staticmethod
    def get_role_menus(role_id):
        """获取角色菜单权限"""
        role = Role.query.get(role_id)
        if not role:
            return None
        
        menu_ids = [menu.id for menu in role.menus]
        return menu_ids
    
    @staticmethod
    def set_role_menus(role_id, menu_ids):
        """设置角色菜单权限"""
        role = Role.query.get(role_id)
        if not role:
            return False
        
        # 删除现有关联
        RoleMenu.query.filter_by(role_id=role_id).delete()
        
        # 添加新关联
        for menu_id in menu_ids:
            role_menu = RoleMenu(role_id=role_id, menu_id=menu_id)
            db.session.add(role_menu)
        
        db.session.commit()
        return True 